package user.models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import search.ArticleSearchEngine;
import search.ArticleSearchModel;
import search.result.ArticleSearchResult;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Article;
import entities.ArticleSearch;

public class ArticleModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String cachePrefix = "user_article_";
	
	private static ArticleModel instance = null;
	
	public static ArticleModel getInstance() {
		if (instance == null) {
			instance = new ArticleModel();
		}
		
		return instance;
	}
	
	private ArticleModel() {
		try {
			ObjectifyService.register(Article.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<Article> listByMyArticle(String ns, String userId, int page, int limit, String language) {
		String currentNs = NamespaceManager.get();
		if (!currentNs.equals(ns)) {
			NamespaceManager.set(ns);
		}
		
		List<Article> articles = new ArrayList<Article>();
		Article article = new Article();
		
		int start = (page - 1) * limit;
		
		String cacheName = cachePrefix  + "ns_" + ns + "_" + userId + "_page_" + page + "_limit_"  + limit + "_language_" + language;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				articles = (List<Article>) cache.get(cacheName);
				//if (articles != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		if (!isCached) {
			articles = ofy.query(Article.class).filter("creator", userId)
						.filter("created !=", "null").filter("language", language)
			 			.order("-created").limit(limit).offset(start).list();
			
			if (cache != null && articles != null) {
				try {
					cache.put(cacheName, articles);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
		NamespaceManager.set(currentNs);
		
		return articles;
	}
	
	public void insert(String ns, Article article) {
		String currentNs = NamespaceManager.get();
		if (!currentNs.equals(ns)) {
			NamespaceManager.set(ns);
		}
		
		ofy.put(article);
		
		//Set search article
		try {
			ArticleSearch articleSearch = ArticleSearch.convert(article);
			ArticleSearchEngine.update(articleSearch);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		NamespaceManager.set(currentNs);
	}
	
	public void delete(String ns, Article article) {
		String currentNs = NamespaceManager.get();
		if (!currentNs.equals(ns)) {
			NamespaceManager.set(ns);
		}
		
		ofy.delete(article);
		
		//Set search article
		try {
			ArticleSearchEngine.remove(article.getId());
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		
		NamespaceManager.set(currentNs);
	}
	
	public Article getArticle(String ns, String id) {
		String currentNs = NamespaceManager.get();
		if (!currentNs.equals(ns)) {
			NamespaceManager.set(ns);
		}
		
		Article article = new Article();
		try {
			article = ofy.get(new Key<Article>(Article.class, id));
		} catch (Exception e) {
			article = null;
		}
		
		NamespaceManager.set(currentNs);
		
		return article;
	}
	
	public Article getArticleByAlias(String ns, String alias, String language) {
		String currentNs = NamespaceManager.get();
		if (!currentNs.equals(ns)) {
			NamespaceManager.set(ns);
		}
		
		Article article = new Article();
		
		String cacheName = cachePrefix + "ns_" + ns + "_alias_" + alias + "_language_" + language;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				article = (Article) cache.get(cacheName);
				if (article != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		if (!isCached) {
			try {
				article = ofy.query(Article.class).filter("alias", alias).filter("language", language).get();
				if (cache != null && article != null) {
					cache.put(cacheName, article);
				}
			} catch (Exception e) {
				article = null;
			}
			
		}
		
		NamespaceManager.set(currentNs);
		
		return article;
	}
	
	public boolean checkArticleExists(String ns, String id) {
		boolean exists = false;
		Article article = getArticle(ns, id);
		if (article != null) {
			exists = true;
		}
		return exists;
	}
	
	public Map<String, Article> getByListId(List<String> ids) {
		Map<String, Article> articles = ofy.get(Article.class, ids);
		
		return articles;
	}
	
	public List<Article> getListByIds(List<String> ids) {
		List<Article> articles = new ArrayList<Article>();
		
		Map<String, Article> ars = ofy.get(Article.class, ids);
		
		for (Map.Entry<String, Article> entry : ars.entrySet()) {
			if (entry.getValue() != null) {
				articles.add(entry.getValue());
			}
		}
		
		return articles;
	}
	
	public boolean checkAliasExists(String ns, String alias, String language) {
		boolean exists = false;
		Article article = getArticleByAlias(ns, alias, language);
		if (article != null) {
			exists = true;
		}
		return exists;
	}
	
	public void removeCacheMyArticle(String ns, String userId, String language) {
		String cacheName = "";
		if (cache != null) {
			for (int i = 0; i < 10; i++) {
				int page = i + 1;
				int limit = 20;
				cacheName = cachePrefix  + "ns_" + ns + "_" + userId + "_page_" + page + "_limit_"  + limit + "_language_" + language;
				try {
					cache.remove(cacheName);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
	}
}
